<?php
/**
 * 附件上传 - JBlog
 *
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: mod_upload.php 523 2010-06-23 10:06:24Z lisijie86 $
*/

$postid = intval($_GET['postid']);

function upload_header() {
	global $postid;
	$tabon[$_GET['ac']] = 'class="on"';
	$menu = "<li {$tabon['upload']}><a href=\"?mod=upload&ac=upload&postid={$postid}\">附件上传</a></li>
		<li {$tabon['post']}><a href=\"?mod=upload&ac=post&postid={$postid}\">本文附件</a></li>";
	if ( is_admin() ) {
		$menu .= "<li {$tabon['all']}><a href=\"?mod=upload&ac=all&postid={$postid}\">附件库</a></li>";
	}
echo <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body ,body td, form, ul {margin:0;padding:0;font-size:12px;font-family:'Verdana';}
a {color:#2366A8;text-decoration:none;}
a:hover {color:red;text-decoration:none;}
input {padding:3px;font-size:12px;margin-right:2px;width:300px;}
.button ,.button:hover {background:#2782D6;border:1px solid;border-color:#ddd #264F6E #264F6E #ddd;color:#fff;height:23px;width:60px;font-size:12px;}
li {margin:0;padding:3px 0;list-style:none;}
li.even {background:#f3f3f3;}
li.even:hover {background:#f0f0f0;}
p {margin:3px 0;}
.tab {width:100%;background:#f0f0f0;overflow:hidden;}
.tab ul {border-bottom:1px solid #ccc;height:25px;}
.tab ul li {float:left;margin:3px 0 0 5px;padding:3px 5px;position:relative;bottom:-1px;}
.tab .on {background:#fff;border:1px solid #ccc;border-bottom:none;}
.multipage {height:20px;overflow:hidden;font-size:12px;}
.multipage span ,.multipage a {display:block;background:#fff;float:left;padding:0 5px;border:1px solid #ccc;margin-right:3px;}
.multipage a:hover {border:1px solid #2782D6;}
.multipage .on {background:#2782D6;color:#fff;font-weight:bold;border-color:#2782D6}
.multipage .go {border:1px solid #ccc;height:15px;width:20px;line-height:15px;padding:0;}
</style>
</head>
<script type="text/javascript">
window.onload = function() {
	try {
		var h1 = document.documentElement.scrollHeight;
		var h2 = document.body.scrollHeight;
		var height = Math.min(h1, h2);
		parent.document.getElementById('upload').height = height;
	} catch (e) {}
}
function to_editor(obj, value) {
	try {
		parent.tinyMCE.getInstanceById(obj).getBody().innerHTML += value;
	} catch(e) {}
}
</script>
<body scroll="no">
<div style="border:1px solid #ccc;">
<div class="tab">
	<ul>{$menu}</ul>
</div>
<div style="padding:5px">
EOT;
}

//上传
if ( $_GET['ac']=='upload' ) {
	
	if ( !is_admin() && !check_perm('blog','upload') ) {
		die(__('对不起，你没有权限执行这项操作。'));
	}
	
	if ( check_submit() ) {
		
		require JBLOG_INC.'class_upload.php';
		require JBLOG_INC.'class_image.php';

		$upload = new Upload();
		$image  = new Image();
		if ( config('watermark') ) {
			$image->waterpic = config('waterpic');
			$image->waterpos = config('waterpos');
			$image->watertrans = config('watertrans');
		}

		$files = $upload->execute('attach');

		if (!$files) {
			upload_header();
			echo '<a href="?mod=upload&ac=upload&postid='.$postid.'">请选择要上传的文件</a>';
		} else {
			$output = '';
			$idarr = array();
			foreach ($files as $file) {
				if ( !$file['err'] ) {
					$attach = array(
						'postid' => $postid,
						'userid' => $_USER['id'],
						'username' => $_USER['name'],
						'originalname' => $file['name'],
						'filepath' => $file['path'],
						'filesize' => $file['size'],
						'filetype' => $file['type'],
						'fileext' => $file['ext'],
						'dateline' => NOW
					);
					$isimage = stristr($file['type'],'image');
					if ( $isimage ) {
						//调整图片大小
						if ( config('autoresize') ) {
							$image->thumb(JBLOG_ROOT.$file['path'], JBLOG_ROOT.$file['path'], config('resizewidth'), config('resizeheight'), false, config('resizefix'));
						}
						//加水印
						if ( config('watermark') ) {
							$image->watermark(JBLOG_ROOT.$file['path']);
						}
						$attach['filesize'] = filesize(JBLOG_ROOT.$file['path']);
					}
					$fileid = $db->insert('attach', $attach);
					$idarr[] = $fileid;
					if ( $isimage ) {
						list($width, $height) = getimagesize(JBLOG_ROOT.$file['path']);
						$txt = '<a href="javascript:;" onclick=\'to_editor("content","'.addcslashes('<p><img src="'.$file['path'].'" alt="'.$file['name'].'" /></p>','"').'")\'>[插入HTML]</a> ';
						$txt .= '<a href="javascript:;" onclick=\'to_editor("content","[img='.$width.','.$height.'][upload='.$fileid.'][/img]")\'>[插入UBB]</a> ';
					} else {
						$txt = '<a href="javascript:;" onclick=\'to_editor("content","'.addcslashes('<a href="'.$file['path'].'" title="'.$file['name'].'">'.$file['name'].'</a>','"').'")\'>[插入HTML]</a> ';
						$txt .= '<a href="javascript:;" onclick=\'to_editor("content","[file][upload='.$fileid.'][/file]")\'>[插入UBB]</a> ';
					}
					$output .= '<li>'.$txt.$file['name'].' --- <span style="color:green">成功</span></li>';
				} else {
					$output .= '<li>'.$file['name'].' --- <span style="color:red">'.$file['errmsg'].'</span></li>';
				}
			}
			//临时存放到cookie，发布文章时更新aid
			$idstr = get_cookie('upload_attachments');
			$idstr = preg_match('/^([0-9]+(,[0-9])?)+$/', trim($idstr)) ? trim($idstr) : '';
			!empty($idstr) && $idstr .= ',';
			$idstr .= implode(',', $idarr);
			set_cookie('upload_attachments', $idstr);
			//输出html
			$output = '<ul>'.$output.'</ul>';
			$output .= '<input type="button" class="button" onclick="window.location.href=\'?mod=upload&ac=upload&postid='.$postid.'\'" value="继续上传" />';
			upload_header();
			echo $output;
		}
		
	} else {
		upload_header();
		echo <<<EOT
	<form name="upload" method="post" action="?mod=upload&ac=upload&postid=$postid" enctype="multipart/form-data">
	<input type="hidden" name="dosubmit" value="yes" />
	<p><input type="file" name="attach[]" /></p>
	<p><input type="file" name="attach[]" /></p>
	<p><input type="file" name="attach[]" /></p>
	<p><input type="submit" class="button" value=" 上 传 " /></p>
	</form>
EOT;

	}
//本文附件
} elseif ( $_GET['ac'] == 'post' ) {
	
	if ( !is_admin() && !check_perm('blog','upload') ) {
		die(__('对不起，你没有权限执行这项操作。'));
	}
	
	upload_header();
	$output = '';
	if ( $postid ) {
		$page = max(1, intval($_GET['page']));
		$pagesize = 10;
		$offset = ($page-1)*$pagesize;
		$url = '?mod=upload&ac=post&postid='.$postid;
		$count = $db->count('attach', "postid = '$postid'");
		$query = $db->query("SELECT id,originalname,filepath,filetype,fileext FROM ".tname('attach')." 
		WHERE postid = '$postid' ORDER BY id DESC LIMIT $offset, $pagesize");
		$i = 0;
		while ( $row = $db->fetch_array($query) ) {
			if ( stristr($row['filetype'],'image') ) {
				list($width, $height) = getimagesize(JBLOG_ROOT.$row['filepath']);
				$htmlval = addcslashes('<p><img src="'.$row['filepath'].'" alt="'.$row['originalname'].'" /></p>','"');
				$ubbval = "[img=$width,$height][upload=$row[id]][/img]";
			} else {
				$htmlval = addcslashes('<a href="'.$row['filepath'].'" title="'.$row['originalname'].'">'.$row['originalname'].'</a>','"');
				$ubbval = "[file][upload=$row[id]][/file]";
			}
			if ( file_exists(JBLOG_ROOT.'images/filetype/'.$row['fileext'].'.gif') ) {
				$icon = 'images/filetype/'.$row['fileext'].'.gif';
			} else {
				$icon = 'images/filetype/unknown.gif';
			}
			$output .= '<li class="'.(++$i%2==0?'even':'odd').'">
			<span style="float:right">
			<a href="javascript:;" onclick=\'to_editor("content","'.$htmlval.'")\'>[插入HTML]</a>
			<a href="javascript:;" onclick=\'to_editor("content","'.$ubbval.'")\'>[插入UBB]</a>
			<a href="?mod=upload&ac=del&id='.$row['id'].'&postid='.$postid.'">[删除]</a>
			</span>
			<img src="'.$icon.'" /><a href="'.$row['filepath'].'" target="_blank">'.$row['originalname'].'</a>
			</li>';
		}
	}
	if ( empty($output) ) {
		echo '本文还没有附件，<a href="?mod=upload&ac=upload&postid='.$postid.'">点击上传</a>';
	} else {
		echo '<ul>',$output,'</ul>';
	}

//附件库
} elseif ( $_GET['ac'] == 'all' ) {
	
	if ( !check_perm('attach','manage') ) {
		die(__('对不起，你没有权限执行这项操作。'));
	}

	initGP(array('year','month','keyword','page'));
	upload_header();
	$mintime = $db->result("SELECT dateline FROM ".tname('attach')." ORDER BY id ASC LIMIT 1");
	$minyear = get_date($mintime?$mintime:NOW, 'Y');
	$curyear = get_date(NOW, 'Y');
	echo '<div style="padding-bottom:5px;">
	<form name="s" method="post" action="?mod=upload&ac=all">';
	echo '<select name="year"><option value=""></option>';
	for ( $i=$minyear; $i<=$curyear; $i++ ) {
		$str = $i == $year ? ' selected="selected"' : '';
		echo '<option value="'.$i.'"'.$str.'>'.$i.'</option>';
	}
	echo '</select>'.__('年').'<select name="month"><option value=""></option>';
	for ( $i=1; $i<=12; $i++ ) {
		$str = $i == $month ? ' selected="selected"' : '';
		echo '<option value="'.$i.'"'.$str.'>'.$i.'</option>';
	}
	echo '</select>'.__('月');
	echo '<input type="text" name="keyword" value="'.stripslashes($keyword).'" style="width:80px" />
	<input type="submit" style="width:50px" name="submit" value="'.__('搜索').'">
	</form></div>';
	$page = max(1, intval($page));
	$pagesize = 10;
	$offset = ( $page - 1 ) * $pagesize;
	$url = "?mod=upload&ac=all&postid={$postid}&year={$year}&month={$month}&keyword=".rawurlencode($keyword);
	$wheresql = '1';
	if ( $year ) {
		if ( $month  ) {
			$month = sprintf('%02d',$month);
			$wheresql .= " AND FROM_UNIXTIME(dateline, '%Y%m') = '{$year}{$month}'";
		} else {
			$wheresql .= " AND FROM_UNIXTIME(dateline, '%Y') = '{$year}'";
		}
	}
	if ( $keyword ) {
		$wheresql .= " AND originalname LIKE '%{$keyword}%'";
	}
	$count = $db->count('attach', $wheresql);
	$sql = "SELECT id,originalname,filepath,filetype,fileext FROM ".tname('attach')." WHERE $wheresql LIMIT $offset, $pagesize";
	$query = $db->query($sql);
	$i = 0;
	while ( $row = $db->fetch_array($query) ) {
		if ( stristr($row['filetype'],'image') ) {
			list($width, $height) = @getimagesize(JBLOG_ROOT.$row['filepath']);
			$htmlval = addcslashes('<p><img src="'.$row['filepath'].'" alt="'.$row['originalname'].'" /></p>','"');
			if ( $width && $height ) {
				$ubbval = "[img=$width,$height][upload=$row[id]][/img]";
			} else {
				$ubbval = "[img][upload=$row[id]][/img]";
			}
		} else {
			$htmlval = addcslashes('<a href="'.$row['filepath'].'" title="'.$row['originalname'].'">'.$row['originalname'].'</a>','"');
			$ubbval = "[file][upload=$row[id]][/file]";
		}
		if ( file_exists(JBLOG_ROOT.'images/filetype/'.$row['fileext'].'.gif') ) {
			$icon = 'images/filetype/'.$row['fileext'].'.gif';
		} else {
			$icon = 'images/filetype/unknown.gif';
		}
		$output .= '<li class="'.(++$i%2==0?'even':'odd').'">
		<span style="float:right">
		<a href="javascript:;" onclick=\'to_editor("content","'.$htmlval.'")\'>[插入HTML]</a>
		<a href="javascript:;" onclick=\'to_editor("content","'.$ubbval.'")\'>[插入UBB]</a>
		</span>
		<img src="'.$icon.'" /> <a href="'.$row['filepath'].'" target="_blank">'.$row['originalname'].'</a>
		</li>';
	}
	if ( empty($output) ) {
		echo '附件库还没有文件，<a href="?mod=upload&ac=upload&postid='.$postid.'">点击上传</a>';
	} else {
		echo '<ul>',$output,'</ul>';
	}
	echo '<p>',multipage(),'</p>';

//删除一个附件
} elseif ( $_GET['ac'] == 'del' ) {

	$id = intval($_GET['id']);
	$file = $db->fetch_one_array("SELECT userid,postid,filepath FROM ".tname('attach')." WHERE id = '$id'");
	if ( (is_admin() && check_perm('attach','manage')) ||  $file['userid'] == $_USER['id'] ) {
		@unlink(JBLOG_ROOT.$file['filepath']);
		$db->query("DELETE FROM ".tname('attach')." WHERE id = '$id'");
		redirect($_USER['refer']);
	} else {
		die(__('对不起，你没有权限执行这项操作。'));
	}
	
}
?>
</div>
</div>
</body>
</html>